package com.jiarong.repository.impl;

import com.jiarong.domain.User;
import com.jiarong.repository.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.util.List;
import java.util.Objects;

/**
 * @author 加绒
 * @date 2021/10/16 0:05
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<User> selectAll() {
        return jdbcTemplate.query("select * from sys_user",
                new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public Long insertUser(User user) {
        // 创建PreparedStatementCreator对象
        PreparedStatementCreator creator = connection -> {
            // 使用原始JDBC完成PreparedStatement组建
            PreparedStatement preparedStatement = connection.prepareStatement("insert into " +
                            "sys_user(id, username, email, password, phoneNum) values (?, ?, ?, ?, ?)",
                    PreparedStatement.RETURN_GENERATED_KEYS);
            preparedStatement.setObject(1, null);
            preparedStatement.setString(2, user.getUsername());
            preparedStatement.setString(3, user.getEmail());
            preparedStatement.setString(4, user.getPassword());
            preparedStatement.setString(5, user.getPhoneNum());
            return preparedStatement;
        };
        // 创建GeneratedKeyHolder对象
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator, keyHolder);
        // 获得生成的主键
        return Objects.requireNonNull(keyHolder.getKey()).longValue();
    }

    @Override
    public void insertUserRoleRelation(Long userId, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role(userId, roleId) values (?, ?)", userId, roleId);
        }
    }

    @Override
    public void deleteUserRoleRelationByUserId(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId = ?", userId);
    }

    @Override
    public void deleteUser(Long userId) {
        jdbcTemplate.update("delete from sys_user where id = ?", userId);
    }

    @Override
    public User login(String username, String password) throws EmptyResultDataAccessException {
        return jdbcTemplate.queryForObject("select * from sys_user where username = ? and password = ?",
                new BeanPropertyRowMapper<>(User.class), username, password);
    }
}
